gRPC 调试的挑战
与 REST API 可以直接用浏览器或 curl 测试不同,gRPC 使用二进制协议(Protocol Buffers),无法直接通过 HTTP 请求测试。需要专门的工具来调试 gRPC 服务。
grpcurl 简介
grpcurl 是一个命令行工具,类似于 curl 但专门用于 gRPC 服务。它可以:
- 列出服务端提供的服务和方法
- 直接调用 gRPC 方法
- 以 JSON 格式发送请求和查看响应
GitHub 仓库:fullstorydev/grpcurl
环境准备
安装 Go 语言环境
grpcurl 基于 Go 开发,需要先安装 Go:
# 方式 1:使用 GVM(Go Version Manager)安装
# GVM 类似于 NVM,用于管理 Go 版本
bash < <(curl -s -S -L https://raw.githubusercontent.com/moovweb/gvm/master/binscripts/gvm-installer)
gvm install go1.22
gvm use go1.22 --default
# 方式 2:使用 Homebrew(macOS)
brew install go
bash
安装 grpcurl
# 方式 1:通过 Go install
go install github.com/fullstorydev/grpcurl/cmd/grpcurl@latest
# 方式 2:通过 Homebrew(macOS)
brew install grpcurl
# 方式 3:直接下载二进制文件
# 从 GitHub Releases 页面下载对应平台的二进制文件
bash
使用 grpcurl 测试 gRPC 服务
列出服务
# 列出所有服务(需要服务端开启 gRPC 反射)
grpcurl -plaintext localhost:5000 list
# 输出示例:
# hero.HeroesService
# grpc.health.v1.Health
bash
列出服务方法
# 列出某个服务的所有方法
grpcurl -plaintext localhost:5000 list hero.HeroesService
# 输出示例:
# hero.HeroesService.FindOne
# hero.HeroesService.FindMany
bash
查看方法描述
# 查看方法的请求和响应类型
grpcurl -plaintext localhost:5000 describe hero.HeroesService.FindOne
# 输出示例:
# hero.HeroesService.FindOne is a method:
# rpc FindOne ( .hero.HeroById ) returns ( .hero.Hero );
bash
调用方法
# 调用 FindOne 方法
grpcurl -plaintext -d '{"id": 1}' localhost:5000 hero.HeroesService/FindOne
# 输出示例:
# {
# "id": 1,
# "name": "钢铁侠"
# }
bash
使用 SSL/TLS
# 使用 CA 证书连接
grpcurl -cacert certs/ca.cer -d '{"id": 1}' grpc.your-domain.com:5000 hero.HeroesService/FindOne
# 使用自签名证书(跳过验证)
grpcurl -insecure -d '{"id": 1}' grpc.your-domain.com:5000 hero.HeroesService/FindOne
bash
使用 proto 文件(服务端未开启反射时)
grpcurl -plaintext -proto hero.proto -import-path ./protos \
-d '{"id": 1}' localhost:5000 hero.HeroesService/FindOne
bash
gRPC Server Reflection
grpcurl 依赖 gRPC Server Reflection 来自动发现服务和方法。NestJS 中需要额外启用:
pnpm add grpc-reflection
bash
// main.ts
import { enableReflection } from 'grpc-reflection';
const app = await NestFactory.createMicroservice<MicroserviceOptions>(...);
// 启用反射(仅开发环境使用)
if (process.env.NODE_ENV !== 'production') {
enableReflection(app);
}
typescript
注意:生产环境建议关闭 Reflection,避免暴露服务接口信息。
三种 gRPC 测试工具对比
| 工具 | 安装方式 | 优点 | 缺点 |
|---|---|---|---|
| OpenSSL | 系统自带 | 无需安装 | 只能测试连接,不能调用方法 |
| grpcurl | Go install / Brew | 命令行工具,适合脚本化测试 | 需要安装 Go 环境 |
| grpc-tools | npm | 生成代码 + 类型安全 | 配置复杂 |
↑